import store from '@/store/'
import * as types from '@/store/mutation-types'
import commonService from '@/services/commonService'
import registService from '@/services/registService'
import { isIOSOriPad } from '@/utils/uaCheck'
// 解析url参数方法
const getUrlQueryParams = url => {
  var params = {},
    results = null,
    url = url || location.href
  var regex = /[?&]([\w]+)=([^&#]*)/g
  while ((results = regex.exec(url)) != null) {
    params[decodeURIComponent(results[1])] = decodeURIComponent(results[2])
  }
  return params
}

export default async (to, from, next) => {
  // 不需要授权就直接跳过
  if (to.meta.skipAuth) return next()
  // 获取URL参数
  let parm = getUrlQueryParams(location.href)
  // 获取授权URL
  let wxredirecturl = window.location.href.split('#')[0].split('?')[0]
  wxredirecturl = wxredirecturl.substr(0, wxredirecturl.length - 1)

  // 存储来源userLoginType：1企业微信、2公众号
  if (parm.cropId) {
    sessionStorage.setItem('userLoginType', 1)
    localStorage.setItem('cropId', parm.cropId)
  }
  // 保存公众号配置id
  if (parm.uuid) {
    parm.appid && localStorage.setItem('appid', parm.appid)
    parm.uuid && localStorage.setItem('uuid', parm.uuid)
    parm.enterpriseId && localStorage.setItem('enterpriseId', parm.enterpriseId)
    parm.registerType && localStorage.setItem('registerType', parm.registerType)
    parm.parentUserId && localStorage.setItem('parentUserId', parm.parentUserId)
    parm.appid && localStorage.setItem('cropId', parm.appid)
    parm.showbags && sessionStorage.setItem('showbags', parm.showbags)
  }
  // 第三方直接跳转，不走授权流程
  // 6.0.4更改，所有的都必须授权
  // if (parm.authorization == '1') {
  //   return next()
  // }

  // 企业微信 、公众号授权
  if (parm.cropId || parm.uuid) {
    //解决苹果返回不刷新的bug
    if (isIOSOriPad()) {
      window.onpageshow = function (event) {
        if (event.persisted || (window.performance && window.performance.navigation.type == 2)) {
          return window.location.reload()
        }
      }
    }
    let cropId = parm.cropId || parm.appid
    localStorage.removeItem("awMasterUserInfo_" + cropId)//清除老的缓存
    // 进注册页面清除用户信息缓存
    let path = ['/wx/invite/register', '/wx/invite/register2']
    if (path.includes(to.path)) {
      localStorage.removeItem("awMasterUserInfo_sass_" + cropId)
      localStorage.removeItem('officialAccountOpenId')
    }
    let awMasterUserInfo = JSON.parse(localStorage.getItem("awMasterUserInfo_sass_" + cropId))
    // 如果当前有用户授权信息，直接跳进去，否则就跳微信授权
    if (awMasterUserInfo) {
      await store.dispatch('getUserInfo', awMasterUserInfo)
      if (!store.getters.jssdkConfig || !store.getters.jssdkConfig.signature) {
        try {
          window.awHelper.wechatHelper.init()
        } catch (e) {
          console.log('[error:window.awHelper.wechatHelper--1]')
        }
      }
      console.log(window.location.href)
      return next()
    } else {
      // 真正跳转URL
      let defaultPathArr = window.location.href.split('#')
      if (defaultPathArr.length > 1) {
        let defaultPath = window.location.href.split('#')[1].split('?')[0]
        if (defaultPath !== '/') {
          localStorage.setItem('defaultPath', defaultPath)
        }
      }
      // 去微信授权
      store.dispatch('getUserInfo', null)
      store.commit(types.WX_JSSDK, null)
      // 授权地址
      let wxurl = ''
      if (sessionStorage.getItem('userLoginType') == '1') {
        wxurl =
          'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
          cropId +
          '&redirect_uri=' +
          encodeURIComponent(wxredirecturl).toLowerCase() +
          '&response_type=code&scope=snsapi_userinfo&state=062882#wechat_redirect';
      } else {
        let component_appid = process.env.VUE_APP_Component_Appid
        wxurl =
          'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
          cropId +
          '&redirect_uri=' +
          encodeURIComponent(wxredirecturl).toLowerCase() +
          '&response_type=code&scope=snsapi_userinfo&state=062882&component_appid=' + component_appid + '#wechat_redirect';
      }
      window.location.href = wxurl
    }
  }
  // 授权完成后获取用户信息
  if (parm.code) {
    let cropId = localStorage.getItem('cropId')
    let awMasterUserInfo = JSON.parse(localStorage.getItem("awMasterUserInfo_sass_" + cropId))
    // 获取用户信息
    if (!awMasterUserInfo) {
      let userInfo = store.getters.userInfo
      let wxAuthObject = ''
      let userLoginType = sessionStorage.getItem('userLoginType')
      if (userLoginType == 1) {
        // 企业微信获取用户信息
        wxAuthObject = await commonService.wxUserInfo(parm.code, cropId)
      } else {
        // 注册页面不获取用户信息
        let path = ['/', '/wx/register', '/wx/error', '/wx/invite/register', '/wx/invite/register2']
        if (path.includes(to.path)) {
          // 缓存微信授权code 去注册
          sessionStorage.setItem('wxcode', parm.code)
          return next()
        }

        if (!sessionStorage.getItem('officialAccountOpenId') && !store.getters.userInfo.token) {
          // 公众号获取用户信息
          wxAuthObject = await registService.getUserInfoByCode({
            code: parm.code,
            uuid: localStorage.getItem('uuid'),
            enterpriseId: localStorage.getItem('enterpriseId')
          })
          console.log(139, wxAuthObject)
          //保存用户openId
          if (wxAuthObject.officialAccountOpenId) {
            sessionStorage.setItem('officialAccountOpenId', wxAuthObject.officialAccountOpenId)
          }
          if (wxAuthObject && wxAuthObject.token) {
            // 更新用户信息
            userInfo = wxAuthObject.userInfo
            userInfo.userLoginType = wxAuthObject.userLoginType
            userInfo.cropId = cropId
            userInfo.articleShareFlag = wxAuthObject.articleShareFlag || '0'
            userInfo.token = wxAuthObject.token
            userInfo.jumpToDynamicDetail = wxAuthObject.jumpToDynamicDetail
            userInfo.selfSupport = wxAuthObject.selfSupport
            userInfo.articleAppId = wxAuthObject.articleAppId
            userInfo.appName = wxAuthObject.appName
            userInfo.appLogo = wxAuthObject.appLogo
            userInfo.belong = wxAuthObject.belong
            userInfo.belongType = wxAuthObject.belongType
            userInfo.uuid = wxAuthObject.uuid
            await store.dispatch('getUserInfo', userInfo)
          } else {
            wxAuthObject.selfSupport && localStorage.setItem('selfSupport', wxAuthObject.selfSupport)
            wxAuthObject.appName && localStorage.setItem('appName', wxAuthObject.appName)
            wxAuthObject.appLogo && localStorage.setItem('appLogo', wxAuthObject.appLogo)
          }
          // 写一写红包、通讯录、发现页面不跳转登录
          let path = ['/', '/write-article', '/custom/addressBook', '/dynamics', '/preview']
          let status = path.includes(to.path)
          if (status) {
            return next()
          }
          // 其他未注册 直接跳登录
          let uuid = localStorage.getItem('uuid')
          let enterpriseId = localStorage.getItem('enterpriseId')
          let url = window.location.href.split('#')[0].split('?')[0] + `#/wx/login?uuid=${uuid}&enterpriseId=${enterpriseId}&officialAccountOpenId=${wxAuthObject.officialAccountOpenId || ''}`
          window.location.href = url
        }
      }
      if (wxAuthObject && wxAuthObject.token) {
        // 更新用户信息
        userInfo = wxAuthObject.userInfo
        userInfo.userLoginType = wxAuthObject.userLoginType
        userInfo.cropId = cropId
        userInfo.articleShareFlag = wxAuthObject.articleShareFlag || '0'
        userInfo.token = wxAuthObject.token
        userInfo.jumpToDynamicDetail = wxAuthObject.jumpToDynamicDetail
        userInfo.selfSupport = wxAuthObject.selfSupport
        userInfo.articleAppId = wxAuthObject.articleAppId
        userInfo.appName = wxAuthObject.appName
        userInfo.appLogo = wxAuthObject.appLogo
        userInfo.belong = wxAuthObject.belong
        userInfo.belongType = wxAuthObject.belongType
        userInfo.uuid = wxAuthObject.uuid
        await store.dispatch('getUserInfo', userInfo)
      }
    } else {
      await store.dispatch('getUserInfo', awMasterUserInfo)
    }
    // 签名
    if (store.getters.userInfo && store.getters.userInfo.token) {
      if (!store.getters.jssdkConfig || !store.getters.jssdkConfig.signature) {
        try {
          window.awHelper.wechatHelper.init()
        } catch (e) {
          console.log('[error:window.awHelper.wechatHelper]')
        }
      }
    }
    next()
  } else {
    let cropId = localStorage.getItem('cropId')
    let awMasterUserInfo = JSON.parse(localStorage.getItem("awMasterUserInfo_sass_" + cropId))
    if (awMasterUserInfo) {
      await store.dispatch('getUserInfo', awMasterUserInfo)
      // 未签名则签名
      if (!store.getters.jssdkConfig || !store.getters.jssdkConfig.signature) {
        try {
          window.awHelper.wechatHelper.init()
        } catch (e) {
          console.log('[error:window.awHelper.wechatHelper]')
        }
      }
    }
    next()
  }

  // if (parm.cropId) {

  //   //解决苹果返回不刷新的bug
  //   if (isIOSOriPad()) {
  //     window.onpageshow = function (event) {
  //       if (event.persisted || (window.performance && window.performance.navigation.type == 2)) {
  //         console.log('ios back')
  //         window.location.reload()
  //         return
  //       }
  //     }
  //   }

  //   let cropId = parm.cropId
  //   localStorage.setItem('cropId', cropId)
  //   localStorage.removeItem("awMasterUserInfo");//清除老的缓存 

  //   let awMasterUserInfo = JSON.parse(localStorage.getItem("awMasterUserInfo_" + cropId));
  //   if (awMasterUserInfo) {// 如果当前有用户授权信息，直接跳进去，否则就跳微信授权
  //     await store.dispatch('getUserInfo', awMasterUserInfo)

  //     if (!store.getters.jssdkConfig || !store.getters.jssdkConfig.signature) {
  //       try {
  //         window.awHelper.wechatHelper.init()
  //       } catch (e) {
  //         console.log('[error:window.awHelper.wechatHelper--1]')
  //       }
  //     }
  //     next()
  //     return
  //   }


  //   store.dispatch('getUserInfo', null)
  //   store.commit(types.WX_JSSDK, null)

  //   let defaultPathArr = window.location.href.split('#')
  //   if (defaultPathArr.length > 1) {
  //     let defaultPath = window.location.href.split('#')[1].split('?')[0]
  //     if (defaultPath !== '/') {
  //       localStorage.setItem('defaultPath', defaultPath)
  //     }
  //   }

  //   let wxurl =
  //     'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
  //     cropId +
  //     '&redirect_uri=' +
  //     encodeURIComponent(wxredirecturl).toLowerCase() +
  //     '&response_type=code&scope=snsapi_userinfo&state=062882#wechat_redirect'
  //   // console.log(wxredirecturl)
  //   window.location.href = wxurl
  // } else {
  //   if (parm.code) {

  //     let cropId = localStorage.getItem('cropId');

  //     let awMasterUserInfo = JSON.parse(localStorage.getItem("awMasterUserInfo_" + cropId));

  //     if (!awMasterUserInfo) {
  //       let cropId = localStorage.getItem('cropId')
  //       let userInfo = store.getters.userInfo

  //       const wxAuthObject = await commonService.wxUserInfo(parm.code, cropId)
  //       console.log(wxAuthObject, 'wxAuthObject')
  //       userInfo = wxAuthObject.userInfo
  //       userInfo.cropId = cropId
  //       userInfo.articleShareFlag = wxAuthObject.articleShareFlag || '0'
  //       userInfo.token = wxAuthObject.token
  //       userInfo.jumpToDynamicDetail = wxAuthObject.jumpToDynamicDetail
  //       await store.dispatch('getUserInfo', userInfo)

  //     } else {
  //       await store.dispatch('getUserInfo', awMasterUserInfo)
  //     }

  //     if (!store.getters.jssdkConfig || !store.getters.jssdkConfig.signature) {
  //       try {
  //         window.awHelper.wechatHelper.init()
  //       } catch (e) {
  //         console.log('[error:window.awHelper.wechatHelper]')
  //         next()
  //       }
  //     }

  //     next()

  //   } else {
  //     next()
  //   }
  // }
}
